<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\Customer;

class CustomerForm extends Model
{
    public $id;
    public $username;
    public $sex;
    public $birthday;
    public $address;
    public $mobileNumber;

	private $_customer;

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
            [['username', 'sex', 'birthday', 'address', 'mobileNumber'], 'required'],
            ['username', 'validateUsername']
		];
	}

    public function __construct($id = null, $config = []) {
        if (!empty($id)) {
            $customer = Customer::findOne($id);
            $this->username = $customer->username;
            $this->sex = $customer->sex;
            $this->birthday = (int)$customer->birthday;
            $this->address = $customer->address;
            $this->mobileNumber = $customer->mobileNumber;
        } else {
            $customer = new Customer();
        }
        $this->_customer = $customer;

        return parent::__construct($config);
    }

    public function validateUsername($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $customer = Customer::find()->where(['username' => $this->username])->one();
            if ($customer) {
                $this->addError($attribute, '此用户名已经存在了');
            }
        }
    }

    public function addOrUpdate()
    {
        $customer = $this->_customer;
        $customer->username = $this->username;
        $customer->sex = $this->sex;
        $customer->birthday = strtotime($this->birthday);
        $customer->address = $this->address;
        $customer->mobileNumber = $this->mobileNumber;

        if ($customer->save(false)) {

            return true;
        } else {

            return false;
        }
    }

}    